/****************************************************************************

    Copyright 2008, 2009  Clark Scheff
    
    This file is part of SchottGunn.

    SchottGunn is free software: you can redistribute it and/or
    modify it under the terms of the GNU General Public License as published
    by the Free Software Foundation version 3 of the License.

    SchottGunn is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with SchottGunn. If not, see http://www.gnu.org/licenses
    
****************************************************************************/

package com.scheffsblend.schottgunn;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.*;
import android.hardware.SensorManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class SchottGunn extends Activity {
	public static final String PREFS_NAME = "SchotGunPrefsFile";

	private SensorManager mSensorManager = null;
	private AudioManager mAudioManager = null;
	private GraphView mGraphView;
	private Menu mMenu;
	private boolean mResumed = false;
	private boolean mFirstRun = true;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mFirstRun = settings.getBoolean("firstRun", true);
        mGraphView = new GraphView(this, mSensorManager, mFirstRun);
        mGraphView.setVibrate(settings.getBoolean("vibrate", true));
        mGraphView.setShowBG(settings.getBoolean("showBG", true));
        mGraphView.setSenseOffset(settings.getInt("sensitivity", 4));
        mGraphView.setLefty(settings.getBoolean("lefty", false));
        setContentView(mGraphView);
    }

    @Override
    protected void onStart() {
    	super.onStart();
    	mGraphView.invalidate();
    }
    
    @Override
    protected void onPause() {
    	mGraphView.pause();
    	super.onPause();
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	if(true == mResumed)
    		mGraphView.resume();
    	mResumed = true;
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putBoolean("firstRun", mGraphView.getFirstRun());
    	editor.putBoolean("vibrate", mGraphView.getVibrate());
    	editor.putBoolean("showBG", mGraphView.getShowBG());
    	editor.putBoolean("lefty", mGraphView.getLefty());
    	// Don't forget to commit your edits!!!
    	editor.commit();
//    	mGraphView.onStop();
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }

/*    // Called only the first time the options menu is displayed.
	// Create the menu entries.
	// Menu adds items in the order shown.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		mMenu = menu;
		menu.add(0, 0, 0, "Instructions");
		menu.add(0, 3, 1, "Sensitivity");
		menu.add(1, 1, 1, "Toggle Vibration");
		menu.add(1,2,0,"Toggle Background");
		return true;
	}

 	// Activity callback that lets your handle the selection in the class.
	// Return true to indicate that you've got it, false to indicate
	// that it should be handled by a declared handler object for that
	// item (handler objects are discouraged for reasons of efficiency).
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()) {
		case 0:
			mGraphView.showInstructions();
			return true;
		case 1:
			boolean vibrate = !mGraphView.getVibrate();
			mGraphView.setVibrate(vibrate);
			if(vibrate)
				Toast.makeText(this, "Vibration On", Toast.LENGTH_SHORT).show();
			else
				Toast.makeText(this, "Vibration Off", Toast.LENGTH_SHORT).show();
			return true;
		case 2:
			mGraphView.setShowBG(!mGraphView.getShowBG());
			return true;
		case 3:
            LayoutInflater factory = LayoutInflater.from(this);
            final View dv = factory.inflate(R.layout.sensedialog, null);
            int sensitivity = 12 - mGraphView.getSenseOffset();
            new AlertDialog.Builder(SchottGunn.this)
                .setTitle("SchottGunn Settings")
                .setIcon(R.drawable.icon)
                .setView(dv)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
    
                         User clicked OK so do some stuff 
                    	SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
                    	int sense = 12 - sb.getProgress();
                    	mGraphView.setSenseOffset(sense);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                         User clicked cancel so do some stuff 
                    }
                })
                .create()
                .show();
            SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
            sb.setProgress((int)sensitivity);
            sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromTouch) {
					// TODO Auto-generated method stub
					int sensitivity = 12 - seekBar.getProgress();
                	mGraphView.setSenseOffset(sensitivity);
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					
				}
            	
            });
         return true;
		}
		return false;
	}
*/	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			switch(event.getKeyCode()) {
			case KeyEvent.KEYCODE_VOLUME_UP:
		        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
		        		AudioManager.ADJUST_RAISE, 
		        		AudioManager.FLAG_SHOW_UI);
				return true;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
		        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
		        		AudioManager.ADJUST_LOWER, 
		        		AudioManager.FLAG_SHOW_UI);
				return true;
			case KeyEvent.KEYCODE_MENU:
	            LayoutInflater factory = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            final View dv = factory.inflate(R.layout.sensedialog, null);
	            final Vibrator vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
	            int sensitivity = 12 - mGraphView.getSenseOffset();
	            boolean showBG = mGraphView.getShowBG();
	            boolean enableVibrate = mGraphView.getVibrate();
	            boolean lefty = mGraphView.getLefty();
	            new AlertDialog.Builder(SchottGunn.this)
	                .setTitle("SchottGunn Settings")
	                .setIcon(R.drawable.icon2)
	                .setView(dv)
	                .setPositiveButton("GET SOME!", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	    
	                        /* User clicked OK so do some stuff */
	                    	SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
	                    	int sense = 12 - sb.getProgress();
	                    	mGraphView.setSenseOffset(sense);
	                    }
	                })
	                .create()
	                .show();
	            SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
	            sb.setProgress((int)sensitivity);
	            sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar seekBar, int progress,
							boolean fromTouch) {
						// TODO Auto-generated method stub
						int sensitivity = 12 - seekBar.getProgress();
	                	mGraphView.setSenseOffset(sensitivity);
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						
					}
	            	
	            });
	            
	            CheckBox cbBackground = (CheckBox) dv.findViewById(R.id.showBackground);
	            cbBackground.setChecked(showBG);
	            cbBackground.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener () {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						mGraphView.setShowBG(isChecked);
						// TODO Auto-generated method stub
						
					}
	            	
	            });
	            
	            CheckBox cbVibrate = (CheckBox) dv.findViewById(R.id.enableVibrate);
	            cbVibrate.setChecked(enableVibrate);
	            cbVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener () {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						mGraphView.setVibrate(isChecked);
						if(isChecked)
							vibrator.vibrate(250);
						// TODO Auto-generated method stub
						
					}
	            	
	            });
	            CheckBox cbLefty = (CheckBox) dv.findViewById(R.id.lefty);
	            cbLefty.setChecked(lefty);
	            cbLefty.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener () {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						mGraphView.setLefty(isChecked);
						// TODO Auto-generated method stub
						
					}
	            	
	            });
	         return true;
			}
		}
		return false;
	}
}